<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RAG Chat</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: Arial, sans-serif;
            height: 100vh;
            display: flex;
            flex-direction: column;
            background-color: #f5f5f5;
            padding-bottom: 100px;
        }

        .top-right {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            padding: 15px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            z-index: 10;
        }

        .top-right label {
            display: block;
            margin: 5px 0;
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }

        .message {
            margin-bottom: 15px;
        }

        .user .message-content {
            background-color: #dcf8c6;
            margin-left: auto;
            border-top-right-radius: 5px;
            border-bottom-left-radius: 5px;
            border-bottom-right-radius: 5px;
        }

        .bot .message-content {
            background-color: #e5e5ea;
            margin-right: auto;
            border-top-left-radius: 5px;
            border-bottom-left-radius: 5px;
            border-bottom-right-radius: 5px;
        }

        .message-content {
            max-width: 70%;
            padding: 10px 15px;
            line-height: 1.4;
            word-wrap: break-word;
            font-size: 16px;
        }

        .image-container img {
            max-width: 100%;
            height: auto;
            margin-top: 10px;
            border-radius: 8px;
        }

        .input-area {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #fff;
            padding: 15px;
            box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 10;
        }

        .input-area textarea {
            width: 70%;
            height: 60px;
            padding: 10px;
            font-size: 16px;
            border-radius: 10px;
            border: 1px solid #ccc;
            resize: none;
        }

        .input-area button {
            margin-left: 10px;
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            background-color: #4CAF50;
            color: white;
            border-radius: 10px;
            cursor: pointer;
        }

        .input-area button:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>

<!-- 右上角：知识库选择 -->
<div class="top-right">
    <h3>选择知识库</h3>
    {% for kb in knowledge_bases %}
    <label>
        <input type="checkbox" name="knowledge_bases" value="{{ kb.know_base_id }}">
        {{ kb.know_base_name }}
    </label><br>
    {% endfor %}
</div>

<!-- 聊天区域 -->
<div class="chat-container" id="chat-box"></div>

<!-- 底部输入框 -->
<div id="input-area">
    <textarea id="question" placeholder="请输入你的问题..."></textarea>
    <button type="button" onclick="sendQuery()">发送</button>
</div>

<script>
    async function sendQuery() {
        const selected = Array.from(document.querySelectorAll('input[name="knowledge_bases"]:checked'))
            .map(cb => cb.value);
        const question = document.getElementById("question").value;

        if (!question.trim()) return;

        // 添加用户消息
        const userMessage = document.createElement("div");
        userMessage.className = "message user";
        const userContent = document.createElement("div");
        userContent.className = "message-content";
        userContent.innerText = question;
        userMessage.appendChild(userContent);
        document.getElementById("chat-box").appendChild(userMessage);

        // 添加系统回复区域
        const botMessage = document.createElement("div");
        botMessage.className = "message bot";
        const botContent = document.createElement("div");
        botContent.className = "message-content";
        botMessage.appendChild(botContent);
        const imageContainer = document.createElement("div");
        imageContainer.className = "image-container";
        botMessage.appendChild(imageContainer);
        document.getElementById("chat-box").appendChild(botMessage);

        // 自动滚动到底部
        document.getElementById("chat-box").scrollTop = document.getElementById("chat-box").scrollHeight;

        // 清空输入框
        document.getElementById("question").value = "";

        // 发送请求
        const reader = await fetch("/chat/rag/query", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({knowledge_bases: selected, question: question})
        }).then(res => res.body.getReader());

        const decoder = new TextDecoder();
        let buffer = "";
        let images_rendered = false;

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split("\n");
            buffer = lines.pop();

            for (const line of lines) {
                if (line.trim() === "") continue;
                try {
                    const data = JSON.parse(line);
                    if (data.images && !images_rendered) {
                        data.images.forEach(img => {
                            const imgElement = document.createElement("img");
                            imgElement.src = img;
                            imageContainer.appendChild(imgElement);
                        });
                        images_rendered = true;
                    } else {
                        botContent.innerText += data.response || "";
                    }
                } catch (e) {
                    console.error("解析失败：", line);
                }
            }
        }

        // 再次滚动到底部（确保图片加载后）
        document.getElementById("chat-box").scrollTop = document.getElementById("chat-box").scrollHeight;
    }
</script>

</body>
</html>